"""matplotlib utils

"""

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import rcParams
matplotlib.use('Agg')

width_bar = .8
height_max = 18
height_min = 6
width_fig, fontsize, height_line, pt_perinch = 0.8, 9, 1.1, 72


class PlotUtil(object):

    def __init__(self, num_items=1, nrows=1, ncols=1,
                 num_colors=1, axis=0):

        self.fontsize = fontsize
        self.axis = axis

        self.height_fig = height_line * num_items * \
            fontsize / width_fig / pt_perinch

        if self.height_fig > height_max:
            self.height_fig = height_max
            self.fontsize = width_fig * self.height_fig * \
                pt_perinch / height_line / num_items

        elif self.height_fig < height_min:
            self.height_fig = height_min

        self.nrows = nrows
        self.ncols = ncols
        self.num_colors = num_colors
        self.colors = cm.get_cmap('gist_'
                                  'rainbow')(np.linspace(0, 1,
                                                         self.num_colors))

        rcParams['font.size'] = self.fontsize
        if axis == 0:
            figsize = (10.43 * self.fontsize, self.height_fig)
        elif axis == 1:
            figsize = (self.height_fig, 1.43 * self.fontsize,)
        self.fig, self.ax = plt.subplots(nrows=self.nrows,
                                         ncols=self.ncols,
                                         figsize=figsize)

    def plot(self, plot_func, *args, **kwargs):
        plot_func(*args, **kwargs)

    def plot_after(self, grid_axis='both'):
        self.plot(plt.grid, True, axis=grid_axis,
                  alpha=.5, linewidth=.1)
        self.fig.tight_layout(pad=5, )

    @staticmethod
    def save(out='tes.pdf'):
        plt.savefig(out)
